package com.foreknow.dao.impl;

import com.foreknow.dao.AdminDao;
import com.foreknow.db.DBManager;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Admin;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class AdminDaoImpl extends BaseDAO implements AdminDao {
    @Override
    public boolean save(Admin ad) throws SQLException {
        String sql="insert into admin(adminName,password) values(?,?)";
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        setConnection(conn);
        int insert = jdbcTemplate.update(sql,ad.getAdminName(),ad.getPasswork());
        return insert==1;
    }

    @Override
    public List<Object> getQueryAll() throws SQLException {
        String sql="select * from admin";
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        setConnection(conn);
        EntityMapping map = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
        List<Object> list=jdbcTemplate.query(sql,map);
        return list;
    }

    @Override
    public Admin getQueryById(int adminId) throws SQLException {
        String sql="select * from admin where adminId=?";
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        setConnection(conn);
        EntityMapping map = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
        List<Object> list = jdbcTemplate.query(sql, map, adminId);
        if (list.size()>0){
           Admin admin= (Admin) list.get(0);
           return admin;
        }
        return null;
    }

    @Override
    public boolean deleteById(int adminId) throws SQLException {
        String sql="delete from admin where adminId=?";
        DBManager db = DBManager.getInstance();
        Connection conn = db.getConnection();
        setConnection(conn);
        int delete = jdbcTemplate.update(sql,adminId);
        return delete==1;
    }
}
